package org.schedule.controller;

import org.schedule.config.Constant;
import org.schedule.entity.Schedule;
import org.schedule.entity.User;
import org.schedule.service.ScheduleService;
import org.schedule.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;


@Controller
public class UserController {

    @Autowired
    private UserService userService;


    @Autowired
    private ScheduleService scheduleService;




    // 返回登录视图
    @GetMapping("/")
    public String login(@RequestParam(value = "logout", required = false) Boolean logout, Model model) {
        if (logout !=null && logout) {
            model.addAttribute("logout", "true");
        }
        return "login";
    }

    // 返回注册视图
    @GetMapping("/register")
    public String register() {
        return "register";
    }


    // 用户登录
    @PostMapping("login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
        User user = userService.login(username, password);
        if (user != null ) {
            return "redirect:/user/home?userId=" + user.getId();
        } else {
            model.addAttribute("message", "账号或密码错误！");
            return "login";
        }
    }


    //用户注册
    @PostMapping("/register")
    public String registerUser(@ModelAttribute User user, Model model) {
        Boolean result = userService.saveUserInfo(user);// 保存用户
        if (result) {
            model.addAttribute("message", "注册成功，请返回登录！");
        } else {
            model.addAttribute("message", "注册失败！");
        }
        return "register"; // 重定向到注册
    }



    //退出
    @RequestMapping("/logout")
    public String logout() {
        return "redirect:?logout=true";
    }


    @RequestMapping("/user/home")
    public String adminHome(Model model, @RequestParam(value = "userId") Integer userId) {
        // 查询当前登录用户信息
        User user = userService.findUserInfoById(userId);
        List<Schedule> schedules = scheduleService.getSchedulesByUserId(userId);
        model.addAttribute("user", user);
        model.addAttribute("schedules", schedules);
        return "userIndex";
    }

    @RequestMapping("/user/{id}")
    @ResponseBody
    public User getUserInfo(@PathVariable Integer id) {
        return userService.findUserInfoById(id);
    }


    // 删除用户信息
    @DeleteMapping("/admin/user/delete/{id}")
    @ResponseBody
    public boolean deleteUser(@PathVariable Integer id) {
        return userService.deleteUserInfo(id);
    }



    // 保存用户
    @PostMapping("/user/save")
    @ResponseBody
    public boolean saveUser(@RequestBody User user) {
        boolean result = userService.saveUserInfo(user);
        if (!result) {
            throw new RuntimeException("用户创建失败！");
        }
        return result;
    }

    // 更新用户信息
    @PostMapping("/user/update")
    @ResponseBody
    public boolean updateUser(@RequestBody User user) {
        return userService.updateUserInfo(user);
    }

    // 根据用户名搜索用户信息
    @GetMapping("/user/search")
    @ResponseBody
    public List<User> searchUser(@RequestParam String username) {
        return userService.findUserInfoListByUsername(username);
    }

    // 用户头像上传
    @PostMapping("/user/uploadAvatar")
    @ResponseBody
    public String uploadAvatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空！");
        }
        try {
            // 创建存储目录
            String avatarDir = Constant.UPLOAD_DIR;
            File uploadDir = new File(avatarDir);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 生成文件名（防止文件名冲突）
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + fileExtension;

            // 保存文件
            File avatarFile = new File(avatarDir + newFileName);
            file.transferTo(avatarFile);
            // 拼接头像访问路径
            return "/uploads/" + newFileName;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败！", e);
        }
    }

}

